package com.jfcloud.mall.storage.service.impl;

import com.jfcloud.common.exception.BussinessException;
import com.jfcloud.mall.storage.domain.JfcloudStorage;
import com.jfcloud.mall.storage.domain.JfcloudStorageLog;
import com.jfcloud.mall.storage.domain.dto.StorageDeductForm;
import com.jfcloud.mall.storage.persistent.JfcloudStorageLogService;
import com.jfcloud.mall.storage.persistent.JfcloudStorageService;
import com.jfcloud.mall.storage.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author zhaojunfu
 * @Title: StorageServiceImpl
 * @ProjectName jfcloud
 * @Description: TODO
 * @date 2020/9/914:51
 */
@Service
@Transactional
public class StorageServiceImpl implements StorageService {

    @Autowired
    private JfcloudStorageService jfcloudStorageService;
    @Autowired
    private JfcloudStorageLogService jfcloudStorageLogService;

//    @GlobalTransactional
    @Override
    public JfcloudStorage deduct(StorageDeductForm form) {
        JfcloudStorage s =jfcloudStorageService.getById(form.getProductId());
        if(s.getStorageNum()<form.getNum()){
            throw new BussinessException("商品库存不足");
        }
        s.setStorageNum(s.getStorageNum()-form.getNum());
        jfcloudStorageService.saveOrUpdate(s);
        //插入日志
        JfcloudStorageLog log = new JfcloudStorageLog();
        log.setCreateTime(LocalDateTime.now());
        log.setProductId(form.getProductId());
        log.setOrderId(form.getOrderId());
        log.setOpt(-1);
        log.setOptNum(form.getNum());
        jfcloudStorageLogService.save(log);
        return s;
    }

}
